<template>
	<view class="box-bg">
		<uni-nav-bar shadow color="#F7F7F7" left-icon="left" backgroundColor="#3485FD" height="65px" title="就近加油"
			@clickLeft="back" />
	</view>
	<view class="nearby_refueling_list_container">
		<view class="top_container">
			<view class="top">
				<input type="text" v-model="inputValue" class="input_model" placeholder="请输入加油站名字">
				<image src="/static/lsh_0202.png" class="search_icon"></image>
				<view class="icon_container">
					<image src="/static/lsh_0203.png" class="icon_change_style"></image>
					<view class="text_container" @click="mapStation">
						<view class="top_text">地图</view>
						<view class="bottom_text">模式</view>
					</view>
				</view>
			</view>
			<view class="gasoline_number_container">
				<view v-for="(gasolineNumber, index) in gasolineNumbers" class="gasoline_number_message">
					{{ gasolineNumber }}</view>
			</view>
			<view class="top_bottom">
				<!-- 顶部底部区域 -->
			</view>
		</view>
		<view class="middle_container">
			<view class="show_gasolineMessages_container">
				<view class="show_gasolineMessages" v-for="(gasolineMessage, index) in filteredGasolineMessages" :key="index">
					<view class="gasolineMessages_top">
						<view class="gasolineMessages_name">{{ gasolineMessage.name }}</view>
						<view class="gasolineMessages_discounts_container">
							<view class="show_gasolineMessages_discount">
								{{ gasolineMessage.message }}
							</view>
						</view>
						<view class="gasolineMessages_distance">
							{{ gasolineMessage.distance }}Km
						</view>
					</view>
					<view class="gasolineMessage_middle">
						<view class="gasolineMessage_image_container">
							<image :src="gasolineMessage.image"></image>
						</view>
						<view class="gasolineMessages_right_container">
							<view class="gasolineMessage_business_houres">{{ gasolineMessage.business_hours }}</view>
							<view class="gasolineMessage_price">{{ gasolineMessage.phone }}</view>
							<view class="gasolineMessage_address_container">
								<view class="gasolineMessage_address">地址：{{ gasolineMessage.address }}</view>
								<image src="/static/lsh_0201.png"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import baseUrl from '@/untils/urlConfig';
import unirequest from '@/untils/unirequest';
import { onLoad } from '@dcloudio/uni-app'
import { computed } from 'vue'  // 新增：引入computed

// 定义响应式数据
const inputValue = ref('')
// 新增：存储原始加油站数据（未过滤）
const originalGasolineMessages = ref([])
const gasolineNumbers = ref(['90#', '92#', '93#', '95#', '97#', '98#'])
const getUserLocation = async () => {
	try {
		const { latitude: currentLat, longitude: currentLng } = await uni.getLocation({ type: 'wgs84' });
		// 关键修改：将获取到的经纬度同步到地图中心变量
		latitude.value = currentLat;
		longitude.value = currentLng;
		userMarker.value.latitude = currentLat;
		userMarker.value.longitude = currentLng;
		// 将用户位置标记合并到mks数组（确保不重复）
		const isUserMarkerExist = mks.value.some(marker => marker.id === -1);
		if (!isUserMarkerExist) {
			mks.value.unshift(userMarker.value);  // 添加到数组最前面（避免被加油站图标覆盖）
		}
		return { userLat: currentLat, userLng: currentLng };
	} catch (error) {
		uni.showToast({
			title: '获取位置失败，请开启定位权限',
			icon: 'none'
		});
		return null;
	}
};
// 计算距离
const mks = ref([]);
const userMarker = ref({
	id: -1,
	latitude: 0,
	longitude: 0,
	width: 30,  // 比加油站图标大，更明显
	height: 30,
	iconPath: '../../static/dw.png'  // 自定义用户位置图标（需提前在static目录添加此图片）
});
const latitude = ref()
const longitude = ref()
//Haversine公式计算经纬度距离（单位：Km）
const getDistance = (lat1, lng1, lat2, lng2) => {
	const R = 6371; // 地球半径（Km）
	const dLat = (lat2 - lat1) * Math.PI / 180;
	const dLng = (lng2 - lng1) * Math.PI / 180;
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLng / 2) * Math.sin(dLng / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	return parseFloat((R * c).toFixed(2)); // 保留两位小数
};
const getStationList = async () => {
	try {
		// 先获取用户位置
		uni.showLoading({ title: '加载中...' });
		const userLocation = await getUserLocation();
		if (!userLocation) {
			uni.hideLoading();  // 位置获取失败时隐藏
			console.log("⚠️ 用户位置获取失败，未授权或设备不支持");
			return;
		}
		// 获取用户经纬度
		const { userLat: currentLat, userLng: currentLng } = userLocation;
		console.log("✅ 用户位置获取成功，经纬度：", userLocation.userLat, userLocation.userLng); // 打印用户位置
		const res = await unirequest({
			url: `${baseUrl}/gas/station/list`,
			method: 'GET'
		});
		console.log("接口返回原始数据：", res.data); // 打印接口原始响应
		if (res.data.code === 200) {
			// 筛选距离小于1km的加油站
			const filteredStations = res.data.rows.filter(station => {
				const distance = getDistance(
					userLocation.userLat,
					userLocation.userLng,
					Number(station.latitude),  // 字符串转数值
					Number(station.longitude)
				);
				return distance < 1; // 只保留距离小于1km的
			});
			console.log("筛选后符合条件的加油站数量：", filteredStations.length); // 打印筛选结果
			originalGasolineMessages.value = filteredStations.map(station => {
				const distance = getDistance(
					userLocation.userLat,
					userLocation.userLng,
					Number(station.latitude),
					Number(station.longitude)
				);
				return {
					name: station.name,
					message: station.message || '暂无优惠',
					image: station.img || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.iyHvAaqm5Q9Qi2gqGDvlsAHaEE?w=242&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.7&pid=3.1&rm=2',
					business_hours: `营业时间：${station.week || '全天营业'}`,
					phone: `联系电话：${station.phone || '暂无电话'}`,
					address: station.address || '未获取到地址',
					distance: distance.toFixed(2)  // 保留2位小数，绑定到页面显示
				};
			});
		} else {
			console.log("⚠️ 接口返回非200状态码，错误信息：", res.data.msg);
		}
		uni.hideLoading();  // 隐藏加载
	} catch (error) {
		console.error("❌ 获取加油站列表异常：", error);
		uni.hideLoading();
	}
};
const filteredGasolineMessages = computed(() => {
    const keyword = inputValue.value.trim().toLowerCase();
    if (!keyword) {
        return originalGasolineMessages.value;  // 无输入时显示全部
    }
    return originalGasolineMessages.value.filter(station => 
        station.name.toLowerCase().includes(keyword)  // 名称包含关键词（不区分大小写）
    );
});
function mapStation(){
	uni.navigateTo({ 
		url: '/pages/lsh_nearby_map/lsh_nearby_map'
	});
}	// 跳转地图
onLoad(() => {
	getStationList();  // 调用获取加油站列表的函数
});
// 返回上一页方法
const back = () => {
	uni.navigateBack()
}
</script>
<style>
.box-bg {
	position: fixed;
	width: 100%;
	top: 0;
	z-index: 1000;
}

.nearby_refueling_list_container {
	width: 100%;
	position: relative;
	top: 116rpx
}

.top_container {
	width: 100%;
	padding-top: 3px;
	padding-bottom: 3px;
	background-color: #3485FD;
}

.top {
	display: flex;
	position: relative;
	top: 4rpx;
	left: -10rpx;
}

.input_model {
	margin-left: 5%;
	width: 75%;
	height: 40px;
	margin-top: 36rpx;
	position: relative;
	padding: 0 80rpx 0 30rpx;
	/* 右侧留出图标空间 */
	border: 1px solid #d3d3d3;
	border-radius: 25px;
	background-color: white;
}

.search_icon {
	position: absolute;
	/* 修正拼写 */
	right: 200rpx;
	/* 替换 margin-left */
	width: 40rpx;
	/* 必须指定尺寸 */
	height: 40rpx;
	top: 52rpx;
}

.icon_container {
	position: relative;
	display: flex;
	right: 12rpx;
}

.text_container {
	position: absolute;
	color: white;
	top: 25rpx;
	left: 70rpx;
}


.icon_change_style {
	height: 140rpx;
	width: 140rpx;
	margin-left: 35rpx;
}

.gasoline_number_container {
	display: flex;
	margin-left: 24rpx;
	margin-top: 25rpx;
}

.gasoline_number_message {
	height: 120rpx;
	width: 399rpx;
	margin-right: 25rpx;
	border: 1px solid white;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	border-radius: 25rpx;
}

.top_bottom {
	height: 200rpx;
}

.top_text,
.bottom_text {
	margin-left: 7rpx;
	font-weight: 600;
}

.bottom_text {
	margin-top: 6rpx;
}

.middle_container {
	position: absolute;
	top: 350rpx;
	width: 100%;
}

.show_gasolineMessages_container {
	width: 100%;
}

.show_gasolineMessages {
	background-color: white;
	width: 90%;
	border-radius: 15rpx;
	margin-left: 5%;
	margin-right: 5%;
	padding: 2rpx 0rpx 20rpx 0rpx;
	margin-bottom: 20rpx;
}

.gasolineMessages_top {
	margin-left: 5%;
}

.gasolineMessages_name {
	margin-top: 25rpx;
	font-weight: 550;
	font-size: 16px
}

.gasolineMessages_discounts_container {
	display: flex;
	gap: 10rpx;
	margin-top: 15rpx;
}

.show_gasolineMessages_discount {
	font-size: 12px;
	background-color: #FF9900;
	color: orangered;
	border-radius: 10rpx;
	width: 80px;
	text-align: center;
}

.gasolineMessage_middle {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	margin-top: 15rpx;
	margin-left: 5%;
}

.gasolineMessage_image_container image {
	height: 330rpx;
	width: 95%;
	border-radius: 20rpx;
	margin-top: -40rpx;
}

.gasolineMessages_right_container {
	margin-left: 20rpx;
}

.gasolineMessage_business_houres {
	margin-top: 15rpx;
	font-size: 30rpx;
}

.gasolineMessage_price {
	color: black;
	font-size: 30rpx;
	margin-top: 15rpx;
}

.gasolineMessage_address_container {
	display: flex;
	margin-top: 15rpx;
}

.gasolineMessage_address {
	font-size: 30rpx;
}

.gasolineMessage_address_container image {
	height: 20px;
	width: 20px;
	margin-left: 20rpx;
	margin-top: 7rpx;
}

.gasolineMessages_distance {
	position: relative;
	right: -500rpx;
	top: -40px;
	font-size: 30rpx;
	color: #3485FD;
}
</style>
